package com.huang.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.eduservice.entity.EduSubject;
import com.huang.eduservice.entity.excel.SubjectData;
import com.huang.eduservice.entity.subject.oneSubject;
import com.huang.eduservice.entity.subject.twoSubject;
import com.huang.eduservice.listener.SubjectExcelListener;
import com.huang.eduservice.mapper.EduSubjectMapper;
import com.huang.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-20
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            InputStream in=file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
                e.printStackTrace();
        }


    }

    @Override
    public List<oneSubject> getAllSubject() {
        QueryWrapper<EduSubject> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapper1);

        QueryWrapper<EduSubject> wrapper2 = new QueryWrapper<>();
        wrapper2.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapper2);

        ArrayList<oneSubject> finallySubject = new ArrayList<>();

        for (int i = 0; i < oneSubjectList.size(); i++) {
            EduSubject eduSubject1 = oneSubjectList.get(i);
            oneSubject oneSubject = new oneSubject();
            BeanUtils.copyProperties(eduSubject1,oneSubject); //将前者复制给后者

            finallySubject.add(oneSubject);

            ArrayList<twoSubject> twoSubjects = new ArrayList<>();
            for (int i1 = 0; i1 < twoSubjectList.size(); i1++) {

                EduSubject eduSubject2 = twoSubjectList.get(i1);
                if(eduSubject2.getParentId().equals(eduSubject1.getId())){
                    twoSubject twoSubject = new twoSubject();
                    BeanUtils.copyProperties(eduSubject2,twoSubject);
                    twoSubjects.add(twoSubject);
                }


            }

            oneSubject.setChildren(twoSubjects);


        }



        return finallySubject;
    }
}
